package com.cnhis.cloudhealth.clidoctorweb.gzip;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Set;

import org.apache.commons.io.FileUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

public class JsonZipper {

	public static void main(String[] args) throws IOException {
		String s_deSchama = "";

		String s = "C:\\Users\\attilax\\Desktop\\6m\\6M.txt";
		String t = FileUtils.readFileToString(new File(s), "gbk");
		JSONObject jo = JSON.parseObject(t);
		JSONArray ja = jo.getJSONArray("list");
		ArrayList<String> head = gethead(ja);

		ArrayList<HashMap> list_new = new ArrayList<>();
		ArrayList<String> list_new_csv = new ArrayList<>();

		// HashMap<String, Object>

		for (Object jo1 : ja) {
			JSONObject jo2 = (JSONObject) jo1;
			HashMap map = new HashMap<>();
			String obj_line="";
			for (String headname : head) {

				map.put(getHeadIdx(headname, head), jo2.get(headname));
				obj_line=obj_line+","+jo2.get(headname);

			}
			list_new.add(map);
			list_new_csv.add(obj_line);
			// System.out.println(keys);
		}

		String jsonString = JSON.toJSONString(list_new);
		FileUtils.write(new File("C:\\Users\\attilax\\Desktop\\6m\\6M_noschama_utf.txt"), jsonString);
		
		
		String jsonString_csv = JSON.toJSONString(list_new_csv);
		FileUtils.write(new File("C:\\Users\\attilax\\Desktop\\6m\\6M_csv_utf.txt"), jsonString_csv);
	
		System.out.println(jsonString);

	}

	private static int getHeadIdx(String headname, ArrayList<String> head) {
		for (int i = 0; i < head.size(); i++) {
			if (head.get(i).equals(headname))
				return i;
		}
		return -1;
	}

	private static ArrayList<String> gethead(JSONArray ja) {
		ArrayList<String> head = new ArrayList<>();
		JSONObject fst = (JSONObject) ja.get(0);
		Set keys = fst.keySet();
		for (Object object : keys) {

			head.add((String) object);
		}
		return head;
	}

}
